<?php
// +----------------------------------------------------------------------
// | NewThink [ Think More,Think Better! ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2018 http://www.newthink.cc All rights reserved.
// +----------------------------------------------------------------------
// | 版权所有：山西创泰网络科技有限公司
// +----------------------------------------------------------------------
// | Author: JiYun Date:2019-07-26 Time:16:22
// +----------------------------------------------------------------------

namespace app\api\controller;

use app\common\service\ControlEmissionService;
use app\common\service\ControlService;
use app\common\service\FlugGasService;
use app\common\service\CommonService;
use app\common\service\control\ControlPlan;

use think\Db;


final class ControlThree extends BaseController
{
    // 保留的精度 用于round函数
    const PRECISION = 3;
    
    public function getEmssion($plan_number)
    {
        //step4:获取企业的减排前和方案值的排放量（主要获取目标排放量）
        $control = new ControlService();
        
        try {
            $tsinghuaPlanName = $control->getConfirmTsinghuaPlanByPlanNumber($plan_number); //预案名称
            return $tsinghuaPlanName;
        } catch (\Exception $e) {
            return false;
        }
    }
    
    /**
     * @throws \MongoDB\Driver\Exception\Exception
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function companyIndustryMonitor()
    {
        $param = $this->request->param();
        if (empty($param['type']) || empty($param['control_mode_id']) || empty($param['plan_number']) || empty($param['region_id'])) {
            $this->error('参数错误');
        }
        //根据预案编号查询方案
        $object_sql  = 'select * from control_plan_from_tsinghua_plan where plan_number = ? and confirm_scheme = 1';
        $object_info = Db::query($object_sql, array($param['plan_number']));
        if (!empty($object_info)) {
            $object_name = $object_info[0]['name'];
        } else {//start zhugeng 2018-08-24
            $object_name = '方案1';//默认方案1
        }//end zhugeng 2018-08-24
        //根据预案编号查询预案名称和管控开始时间
        $plan_sql     = 'select plan_name,control_start_time,control_end_time from control_plan_name where plan_number = ?';
        $planNameInfo = Db::query($plan_sql, array($param['plan_number']));
        if (!empty($planNameInfo)) {
            $end_date   = date('Y-m-d', strtotime('-2 day', strtotime($planNameInfo[0]['control_start_time'])));
            $start_date = date('Y-m-d', strtotime('-6 day', strtotime($end_date)));
        }
        $flug = new FlugGasService();
        $emission                = new ControlEmissionService();
        $res = $this->getEmssion($param['plan_number']); //预案名称
        
        if (!$res) {
            $tsinghuaPlanName        = 0;
            $targetEmissionReduction = [];
        } else {
            $tsinghuaPlanName = $res;
            
            // 目标减排量

            $controlModeId    = isset($param['control_mode_id']) ? $param['control_mode_id'] : 1;  //类型,默认为工业减排
            $type             = $param['type'];  //类型
            $planNumber       = $param['plan_number'];  //预案编号
    
            //step2:查询
            $where = [
                'plan_number' => $planNumber,
                'control_mode_id' => $controlModeId,
                // 'tsinghua_plan_name' => $tsinghuaPlanName,
                'tsinghua_plan_name' => $param['plan_id'],
                'type' => $type,
            ];
            $targetEmissionReduction  = db::name('control_step_two_get_drain_emissions')
                ->field('*')
                ->where($where)
                ->select();
        }
        
        $controlPlan   = new ControlPlan();
        $commonService = new CommonService();
        
        //企业列表
        $limit        = $flug->page($param['page'], 5);
        $sql          = 'select type,is_realtime,plan_number,company_id,drain_id,drain_name,tracking_type from control_setting_list where type = ? and plan_number = ? and control_status = 0 and region_id = ? and tracking_type = ? order by company_id asc limit ?,?';
        $company_list = Db::query($sql, array($param['type'], $param['plan_number'], $param['region_id'], $param['control_mode_id'], $limit, 5));
        
        $result = [];
        
        $before = $controlPlan->getBeforeControlCompanyPollutent($param['control_start_time'], $param['control_end_time'], $param['station_id']);
        $after  = $controlPlan->getControlCompanyPollutent($param['control_start_time'], $param['control_end_time'], $param['plan_id'], $param['plan_number'], $param['station_id']);
        
        if (!empty($company_list)) {
            foreach ($company_list as $k => $v) {
                //根据公司id查询公司名
                $company_sql = 'select name,short_name from basic_company where id = ?';
                $companyInfo = Db::query($company_sql, array($v['company_id']));
                if (!empty($companyInfo)) {
                    $company_list[$k]['company_name'] = $companyInfo[0]['name'];
                }
                //update-start zhugeng 2019-08-24
                //获取减排前排口排放量(模拟企业和实时企业)
                $emissions = $emission->getSingleDrainEmissionsHourAvg($v['drain_id'], $param['plan_number']);
                if (!empty($emissions)) {
                    if ($param['type'] == 'SO2') {
                        $emissions = $emissions['so2_emissions'];
                    } else {
                        $emissions = $emissions['nox_emissions'];
                    }
                }
//                foreach ($targetEmissionReduction as $k1 => $v1) {
//                    if ($v['drain_id'] == $v1['drain_id']) {
//                        $emissions = $v1['origin_emissions'];
//                    }
//                }
//                if (!isset($emissions)) {
//                    $emissions = 1;
//                }
                //update-end zhugeng 2019-08-24
                //运行浓度减排前值
                // $concentration_before                     = round($flug->beforeConcentration($start_date, $end_date, $v['company_id'], $v['drain_id'], $param['type'], $param['plan_number'], $v['is_realtime'], $object_name), 3);
                $concentration_before                     = round($flug->beforeConcentration($start_date, $end_date, $v['company_id'], $v['drain_id'], $param['type'], $v['is_realtime'], $emissions), self::PRECISION);
                $company_list[$k]['concentration_before'] = $concentration_before;
                //运行效率减排前值
                // $company_list[$k]['efficiency_before'] = round($flug->getCompanyFacilityOperatingEfficiency($param['plan_number'], $v['drain_id'], $param['type'], $end_date, 7, $v['is_realtime'], $object_name), 3);
                $company_list[$k]['efficiency_before'] = round($flug->getCompanyFacilityOperatingEfficiency($v['drain_id'], $param['type'], $end_date, 7, $v['is_realtime'], $emissions), self::PRECISION);
                //update-start zhugeng 2019-08-24
                //获取清华方案排放量(模拟企业和实时企业)
                $emission_drain = $flug->getQingHuaEmissionDrainDayAvg($param['plan_number'], $param['control_mode_id'], $object_name, $v['company_id'], $v['drain_id'], $param['type'], $v['is_realtime']);
                if (!empty($emission_drain)) {
                    $qinghua_hour_avg = $emission_drain;
                } else {
                    $qinghua_hour_avg = 0;
                }
                //获取清华方案排放量
//                foreach ($targetEmissionReduction as $k1 => $v1) {
//                    if ($v['drain_id'] == $v1['drain_id']) {
//                        // $qinghua_hour_avg = $v1['plan_emissions'];
//                        $qinghua_hour_avg = $v1['tsinghua_emissions'];
//                    }
//                }
//                if (!isset($qinghua_hour_avg)) {
//                    $qinghua_hour_avg = 1;
//                }
                //update-end zhugeng 2019-08-24
                //运行浓度方案值
                $company_list[$k]['concentration_project'] = round($flug->beforeProjectValue($planNameInfo[0]['control_start_time'], $planNameInfo[0]['control_end_time'], $v['company_id'], $v['drain_id'], $param['type'], $v['is_realtime'], $qinghua_hour_avg), self::PRECISION);
                //运行效率方案值
                $company_list[$k]['efficiency_project'] = round($flug->getCompanyFacilityOperatingiDscharge($planNameInfo[0]['control_start_time'], $planNameInfo[0]['control_end_time'], $v['drain_id'], $param['type'], $v['company_id'], $v['is_realtime'], $qinghua_hour_avg), self::PRECISION);
                
                // 贡献度减排前
                $contributionDegreeSum = 0;
                $concentrationSum      = 0;
                foreach ($before as $d) {
                    if (($d['company_id'] == $v['company_id'])
                        && ($d['contribution_name'] == $param['contribution'])) {
                        $contributionDegreeSum += $d['contribution_degree'];
                        $concentrationSum      += $d['concentration'];
                    }
                }
                if ($concentrationSum != 0) {
                    $company_list[$k]['before'] = round($commonService->contributionRound($contributionDegreeSum / $concentrationSum), self::PRECISION);
                } else {
                    $company_list[$k]['before'] = '-';
                }
                
                // 贡献度减排后
                $contributionDegreeSum = 0;
                $concentrationSum      = 0;
                foreach ($after as $d) {
                    if (($d['company_id'] == $v['company_id'])
                        && ($d['contribution_name'] == $param['contribution'])) {
                        $contributionDegreeSum += $d['contribution_degree'];
                        $concentrationSum      += $d['concentration'];
                    }
                }
                if ($concentrationSum != 0) {
                    $company_list[$k]['after'] = round($commonService->contributionRound($contributionDegreeSum / $concentrationSum), self::PRECISION);
                } else {
                    $company_list[$k]['after'] = '-';
                }
                
                if ($company_list[$k]['after'] != '-'
                        && $company_list[$k]['after'] != '0') {
                    // 贡献度削减率
                    $company_list[$k]['degreeOfReduction'] = round(($company_list[$k]['before'] - $company_list[$k]['after']) / $company_list[$k]['before'], self::PRECISION);
                } else {
                    $company_list[$k]['degreeOfReduction'] = '-';
                }
                
                // 目标减排量
                $company_list[$k]['targetEmissionReduction'] = 0;
                
                foreach ($targetEmissionReduction as $target) {
                    if ($target['drain_id'] == $v['drain_id']) {
                        $company_list[$k]['targetEmissionReduction'] = round($target['target_emissions'], self::PRECISION);
                    }
                }
            }
            $result['data'] = $company_list;
            // 目标总减排量
            $result['total'] = round(array_sum(array_column($company_list, 'targetEmissionReduction')), self::PRECISION);
            // 减排前平均贡献度
            $before              = array_column($company_list, 'before');
            $result['beforeAvg'] = round(array_sum($before) / count($before), self::PRECISION);
            
            // 减排后平均贡献度
            $after              = array_column($company_list, 'after');
            $result['afterAvg'] = $after[0] == '-' ? '-' : round(array_sum($after) / count($after), self::PRECISION);
            // 贡献度平均削减率
            $reduction              = array_column($company_list, 'degreeOfReduction');
            $result['reductionAvg'] = $reduction[0] == '-' ? '-' : round(array_sum($reduction) / count($reduction), self::PRECISION);
            
            $sql_all         = 'select type,is_realtime,plan_number,company_id,drain_id,drain_name,tracking_type from control_setting_list where type = ? and plan_number = ? and control_status = 0 and region_id = ? and tracking_type = ?';
            $list_all        = Db::query($sql_all, array($param['type'], $param['plan_number'], $param['region_id'], $param['control_mode_id']));
            $result['count'] = count($list_all);
        }
        
        $this->success('成功', $result);
    }
}
